<!--
 * @Author: fj
 * @LastEditors: root zhangpengpeng@ikingtech.com
 * @description:
 * @updateInfo: 本次更新内容：
 * @Date: 2024-03-01 14:39:12
 * @LastEditTime: 2024-03-26 16:46:54
-->
<template>
  <div class="manage-main flex">
    <div class="dept">
      <div class="title">项目列表</div>
      <n-tree
        block-line
        :data="demparentist"
        default-expand-all
        key-field="id"
        label-field="name"
        selectable
        @update:selected-keys="handleDepChange"
      />
    </div>
    <div class="user-list">
      <div class="title">
        <span> 用户列表 </span>
        <div class="right-title">
          <n-button secondary @click="addHandle(null)">新增</n-button>
          <div class="search">
            <n-input
              v-model:value="searchForm.username"
              clearable
              class="search-input"
              placeholder="搜索"
            />
          </div>
          <n-icon class="icon-search">
            <IconSearch @click="getUserList" />
          </n-icon>
        </div>
      </div>
      <div>
        <n-data-table
          :columns="columns"
          :data="userList"
          :pagination="paginationReactive"
          :bordered="false"
          :loading="loading"
        />
      </div>
    </div>
    <!-- 新增编辑 -->
    <UserManagementEdit
      v-model="visible"
      :dept-id="searchForm.deptId"
      :edit-data="editData"
      @getList="getUserList"
    />
  </div>
</template>
<script lang='ts'>
import {
  NTree,
  NButton,
  NDropdown,
  NDataTable,
  useDialog,
  useMessage,
  NUpload,
  NUploadDragger,
  NSpin,
  NTag,
} from "naive-ui";
import { IconDelete, IconEdit, IconMoreVh, IconSearch } from "@/icons";
import { useProjectStore } from "@/store/project";
import { sysApi } from "@/api/user";
import { userApi } from "@/api/system";
import UserManagementEdit from "./edit-form.vue";

export default defineComponent({
  name: "UserManagement",
  components: {
    UserManagementEdit,
    NTree,
    NDataTable,
    IconSearch,
  },

  setup() {
    const nDialog = useDialog();
    const projectStore = useProjectStore();
    projectStore.request();
    const demparents = computed(() => projectStore.lists);
    const demparentist = computed(() => projectStore.groups);
    watch(
      () => projectStore.groups,
      (val) => {
        if (!selectDep.value) {
          selectDep.value = val[0];
        }
      }
    );
    const enum DepOper {
      新建子项目 = "newProject",
      重命名 = "rename",
      移动 = "move",
      删除 = "delete",
    }

    const nMessage = useMessage();

    const searchForm = reactive({
      deptId: "",
      username: "",
    });
    const selectDep = ref();

    const depObj = reactive({
      addModal: false,
      renameModal: false,
      moveModal: false,
      editing: false,
      addRules: {
        name: [
          { required: true, message: "请输入项目名称", trigger: ["change"] },
        ],
      },
      demparent: {
        name: "",
        parentId: "",
      },
      depRename: {
        name: "",
        id: "",
      },
    });

    const editData = ref({});
    const loading = ref(false);
    const userList = ref([]);
    const columns = [
      {
        title: "用户名",
        key: "username",
      },
      {
        title: "项目名称",
        render(row) {
          return h(
            "div",
            {},
            {
              default: () => row.departments.map((it) => it.deptName).join(""),
            }
          );
        },
      },
      {
        title: "手机号",
        key: "phone",
      },
      {
        title: "状态",
        key: "locked",
        render(row) {
          return h("div", {}, [
            row.locked === false
              ? h(
                  NTag,
                  {
                    type: "success",
                  },
                  { default: () => "未锁定" }
                )
              : h(
                  NTag,
                  {
                    type: "error",
                  },
                  { default: () => "已锁定" }
                ),
          ]);
        },
      },
      {
        title: "操作",
        key: "",
        width: 260,
        align: "center",
        render(row) {
          return h("div", {}, [
            h(
              NButton,
              {
                strong: true,
                quaternary: true,
                size: "small",
                onClick: () => {
                  addHandle(row);
                },
              },
              { default: () => "编辑" }
            ),
            h(
              NButton,
              {
                strong: true,
                quaternary: true,
                size: "small",
                type: "warning",
                onClick: () => {
                  deleteUser(row);
                },
              },
              { default: () => "删除" }
            ),
          ]);
        },
      },
    ];
    const paginationReactive = reactive({
      page: 1,
      pageSize: 20,
      showSizePicker: true,
      pageSizes: [20, 40, 60],
      onChange: (page: number) => {
        paginationReactive.page = page;
      },
      onUpdatePageSize: (pageSize: number) => {
        paginationReactive.pageSize = pageSize;
        paginationReactive.page = 1;
      },
    });

    const visible = ref(false);
    // 点击项目列表触发
    const handleDepChange = (val) => {
      selectDep.value = demparents.value.find((v) => v.id === val[0]);
      searchForm.deptId = selectDep.value?.id || "";
      getUserList();
    };
    // 查询用户
    const getUserList = async () => {
      try {
        loading.value = true;
        const res = await userApi.getUserList({
          ...searchForm,
          deptIds: [searchForm.deptId],
          page: paginationReactive.page,
          rows: paginationReactive.pageSize,
        });
        loading.value = false;
        if (res.success) {
          userList.value = res.data || [];
        } else {
          nMessage.error(res.msg);
          userList.value = [];
        }
      } catch (error) {
        loading.value = false;
        nMessage.error(error.message);
      }
    };
    // 新增，修改
    const addHandle = (obj: any) => {
      editData.value = { ...obj };
      nextTick(() => {
        visible.value = true;
      });
    };

    // 删除用户
    const deleteUser = (row: any) => {
      const d = nDialog.create({
        title: "确认删除",
        content: `删除后，用户【${row.username}】将不能使用本系统，无法恢复。确定删除吗？`,
        negativeText: "取消",
        positiveText: "确定",
        showIcon: false,
        onPositiveClick: async () => {
          d.loading = true;
          try {
            const res = await userApi.deleteUsers(row.id);
            if (res.success) getUserList();
            else nMessage.warning(res.msg);
          } catch (error) {
            nMessage.error(error.message);
          }
        },
      });
    };

    onMounted(() => {
      getUserList();
    });

    return {
      demparentist,
      handleDepChange,
      addHandle,
      columns,
      visible,
      userList,
      paginationReactive,
      getUserList,
      searchForm,
      editData,
      deleteUser,
    };
  },
});
</script>
<style lang="scss" scoped>
@import "../style.scss";
</style>
